package sm.upgrade.api.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;

import sm.def.KeyType;
import sm.hibernate.DAMUtil;
import sm.upgrade.api.KeyValidator;
import sm.util.SMMap;
import sm.util.Util;

public class NewKeyValidator extends AbstractKeyValidator {

	private static Logger logger = LoggerFactory.getLogger(KeyValidator.class);

	private HibernateTemplate template;

	public NewKeyValidator(HibernateTemplate template) {
		this.template = template;
	}

	@Override
	public boolean resolveConflict(String fileName, SMMap dataMap,
			String keyStr, int keyType, String[] keyPaths,
			Object[] oldKeyValue, Object[] newKeyValue) {
		logger.warn("Fix conflict of " + KeyType.getType(keyType).getName()
				+ " key " + Util.formatKey(oldKeyValue) + " to "
				+ Util.formatKey(newKeyValue));
		SMMap clonedDataMap = (SMMap) dataMap.clone();
		DAMUtil.setValues(clonedDataMap, keyPaths, newKeyValue);

		String entityName = Util.radEntityNameToJava(fileName);

		template.delete(entityName, dataMap);
		template.save(entityName, clonedDataMap);
		return false;
	}

}
